import 'package:flutter/cupertino.dart';
import 'package:mvvm_provider/page/novel/states/novel_detail_state.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../base/base_view_model.dart';
import '../../../model/response_model.dart';
import '../../../net/ltt_https.dart';
import '../../../net/http_config.dart';
import '../model/content_model_entity.dart';
import '../model/tabs_model_entity.dart';

class NovelDetailViewModel extends BaseViewModel {
  NovelDetailState state = NovelDetailState();

  Map<String, dynamic> params = {
    'appkey': 'da44a5d9227fa9ef',
    'mobi_app': 'iphone_comic',
    'version': '5.11.0',
    'build': '1700',
    'channel': 'AppStore',
    'platform': 'ios',
    'device': 'phone',
    'buvid': 'Z2478A2AC97B74224D3FBE96297C8DF6FA4D',
    'machine': 'iPhone+13',
    'access_key':
        '4190755842052a685fd9f55724dbafa2CjDdaOgQ9baMW_QFtYv0tGUPEDeMGW54gRKLalyMVYymTpnrB5nLTWeHy_12rg_4GOgSVlVzUjdlS0lWRi1zSEJ0WEZRejdSSHQwakVmYUMxWmNadVItRzJNNFkyOTdpN0w5WmJ4ZXBZdE44ZU1uUTBTOEVCQjcwUVpBSU1RaWZlUy1aQnlZQmpnIIEC',
    'is_teenager': 'is_teenager',
    'no_recommend': '0',
    'network': 'wifi',
    'ts': '1697097473',
  };

  Future<void> getTabsData() async {
    ResponseModel? responseModel = await LttHttp().request<TabsModelData>(
        'https://manga.bilibili.com/twirp/comic.v1.Comic/ListRank',
        params: params,
        method: HttpConfig.post);
    TabsModelData tabsModelData = responseModel.data;
    state.tabsList = tabsModelData.list;
    notifyListeners();
  }

  Future<void> getContentData({int id = 7}) async {
    params.addAll({'id': id, "offset": 0, "subId": 0});
    ResponseModel? responseModel = await LttHttp().request<ContentModelData>(
        'https://manga.bilibili.com/twirp/comic.v1.Comic/GetRankInfo',
        params: params,
        method: HttpConfig.post);
    ContentModelData contentModelData = responseModel.data;
    state.contentList = contentModelData.list;

    scrollController.animateTo(0,
        duration: const Duration(milliseconds: 400), curve: Curves.easeIn);
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    notifyListeners();
  }

  /// 改变左边点击tab
  void changeIndex(int index) {
    if (index == state.selectIndex) return;
    if (index >= state.tabsList.length) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      refreshController.loadNoData();
      return;
    }
    if (index < 0) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      return;
    }
    state.selectIndex = index;
    getContentData(id: state.tabsList[index].id);
  }
}
